import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AdvisePage extends StatefulWidget {
  @override
  _AdvisePageState createState() => _AdvisePageState();
}

class _AdvisePageState extends State<AdvisePage> {
  bool _loading = false;

  var _contentController = TextEditingController();
  var _contactController = TextEditingController();

  //选择图片相关
  List<Widget> list;
  List<File> listPics;
  List<String> fileList;
  double picWidth = (Comm.screenWidth - 80) / 4.0;
  String fileName = "";

  String _msg = "";

  @override
  void initState() {
    super.initState();
    list = List<Widget>()..add(_buildPicButton());
    listPics = List<File>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1.0,
        backgroundColor: Theme.of(context).canvasColor,
        titleSpacing: 0.0,
        title: Text(
          "意见反馈",
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: ProgressDialog(
        msg: _msg,
        loading: _loading,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _titleWidget(),
              Divider(),
              _contentWidget(),
              Divider(),
              _picHintWidget(),
              Divider(),
              _addPicture(),
              Divider(),
              _contactHintWidget(),
              Divider(),
              _contactWidget(),
              Divider(),
              _submitWidget(),
            ],
          ),
        ),
      ),
    );
  }

  ///顶部标题栏
  Widget _titleWidget() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      child: Text(
        "问题和意见",
        style: TextStyle(color: Colors.grey),
      ),
    );
  }

  ///内容
  Widget _contentWidget() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
      child: TextField(
        maxLength: 200,
        maxLines: 4,
        textAlign: TextAlign.start,
        controller: _contentController,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(top: 10),
          hintText: "请用10-400字简要描述您遇到的问题",
          hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///图片说明
  Widget _picHintWidget() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
      child: Row(
        children: <Widget>[
          Text("图片（选填，提供问题截图）", style: TextStyle(color: Colors.grey)),
          Expanded(child: Container()),
          Text("${listPics.length}/3", style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }

  ///添加图片
  Widget _addPicture() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      width: double.infinity,
      child: Wrap(
        children: list,
        spacing: 10,
        runSpacing: 10,
      ),
    );
  }

  ///联系方式提示
  Widget _contactHintWidget() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
      child: Text(
        "联系方式(选填)",
        style: TextStyle(color: Colors.grey),
      ),
    );
  }

  ///联系方式
  Widget _contactWidget() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
      child: TextField(
        textAlign: TextAlign.start,
        controller: _contactController,
        decoration: InputDecoration(
          hintText: "QQ/微信/邮箱",
          hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///提交按钮
  Widget _submitWidget() {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.only(left: 20, right: 20, top: 20, bottom: 40),
      decoration: BoxDecoration(
        color: Theme.of(context).accentColor,
        borderRadius: BorderRadius.circular(6),
      ),
      child: FlatButton(
        child: Text(
          '提交反馈',
          style: TextStyle(color: Colors.white),
        ),
        onPressed: () {
          if (listPics.isNotEmpty) {
            _uploadImage(listPics);
          } else {
            _submit();
          }
        },
      ),
    );
  }

  ///构建添加图片按钮
  Widget _buildPicButton() {
    return GestureDetector(
      onTap: () {
        if (listPics.length >= 3) {
          Toast.show("最多可选3张图片");
          return;
        }
        showModalBottomSheet(
            backgroundColor: Colors.transparent,
            context: context,
            builder: (builder) {
              return _choicePic();
            });
      },
      child: Container(
        width: picWidth,
        height: picWidth,
        color: Color(0xffEEEEEE),
        child: Icon(
          Icons.add,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  ///选择图片对话框
  Widget _choicePic() {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.all(10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: Column(children: <Widget>[
            FlatButton(onPressed: _openCamera, child: Text('拍照')),
            Divider(height: 1, color: Color(0xffBBBBBB)),
            FlatButton(onPressed: _openAlbum, child: Text('从相册中选择'))
          ])),
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ))
    ]);
  }

  ///打开相册
  Future _openAlbum() async {
    print('打开相册');
    Navigator.pop(context);
    AssetPicker.pickAssets(context,
            maxAssets: 3 - listPics.length,
            themeColor: Theme.of(context).accentColor)
        .then((List<AssetEntity> assets) {
      assets.forEach((AssetEntity asset) async {
        File image = await asset.file;
        listPics.add(image);
        setState(() {
          list.insert(list.length - 1, _buildPhoto(image));
        });
      });
    });
  }

  ///打开相机
  void _openCamera() async {
    Navigator.pop(context);
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    listPics.add(image);
    setState(() {
      list.insert(list.length - 1, _buildPhoto(image));
    });
  }

  ///构建图片
  Widget _buildPhoto(File image) {
    return Stack(
        overflow: Overflow.visible,
        alignment: Alignment(0.9, -0.9),
        children: <Widget>[
          Container(
            width: picWidth,
            height: picWidth,
            child: Image.file(
              image,
              width: picWidth,
              height: picWidth,
              fit: BoxFit.cover,
            ),
          ),
          GestureDetector(
            onTap: () {
              var index = listPics.indexOf(image);
              setState(() {
                listPics.removeAt(index);
                list.removeAt(index);
              });
            },
            child: Container(
              width: 18,
              height: 18,
              decoration: BoxDecoration(
                  color: Color(0x7f000000),
                  borderRadius: BorderRadius.circular(9)),
              child: Icon(
                Icons.clear,
                color: Colors.white,
                size: 12,
              ),
            ),
          )
        ]);
  }

  ///上传图片
  Future _uploadImage(List<File> files) async {
    setState(() {
      _loading = true;
      _msg = "上传中...";
    });
    Http.upload(Api.URL_UPLOADS, files, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      print("上传结果：" + data);
      jsonDecode(data).forEach((item) {
        fileName = "$fileName${item["path"]},";
      });
      if (fileName.endsWith(",")) {
        fileName = fileName.substring(0, fileName.length - 1);
      }
      _submit();
    }, errorCallBack: (errorMsg) {
      setState(() {
        _loading = false;
      });
    });
  }

  ///发布话题
  void _submit() async {
    if (_loading) return;
    String contact = _contactController.text;
    String content = _contentController.text;
    if (content.isEmpty) {
      Toast.show("反馈意见不能为空");
      return;
    }
    setState(() {
      _msg = "发布中...";
      _loading = true;
    });
    Map<String, String> params = Map();
    params["content"] = content;
    if (contact.isNotEmpty) {
      params["contact"] = contact;
    }
    if (fileName.isNotEmpty) {
      params["images"] = fileName;
    }
    Http.post(Api.URL_ADVISE_ADD, params: params, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      Toast.show("反馈成功");
      Routers.router.pop(context);
    }, errorCallBack: (error) {
      setState(() {
        _loading = false;
      });
    });
  }
}
